package com.xinhe.cn.cpbox.controller;


import com.xinhe.cn.cpbox.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: HB
 * @date: 2021/02/20
 * @description: 全局错误处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionController {
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Object mismatchErrorHandler(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        log.error("url:{}\n 参数转换失败，信息：{}", request == null ? null : request.getRequestURL(), e.getLocalizedMessage());
        return Result.paramError().message("参数undefined");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public Object fileUploadSizeErrorHandler(MaxUploadSizeExceededException e, HttpServletRequest request) {
        log.error("上传的单个文件大小过大");
        return Result.paramError().message("上传的单个文件大小过大");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Object illegalArgumentErrorHandler(IllegalArgumentException e, HttpServletRequest request) {
        log.error("请求中有非法字符");
        return Result.paramError().message("请求中有非法字符");
    }
}
